package pt.utl.ist.ginger3d.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class PlaceHolderBlock extends Block implements IBlockSet {

	public int minOccurs = 1, maxOccurs = 1;
	private Map<String, Block> blockMap;
	private List<PlaceHolderBlock> placeHolders;
	
	public PlaceHolderBlock(String templateName, Collection<Block> blocks, Map<String, String> properties) {
		
		super(templateName, "place-holder", properties);
		
//		if(properties.get("min-occurs") != null) {
//			minOccurs = Integer.parseInt(properties.get("min-occurs"));
//		}
//		
//		if(properties.get("max-occurs") != null) {
//			maxOccurs = Integer.parseInt(properties.get("max-occurs"));
//		}
		
		blockMap = new LinkedHashMap<String, Block>();
		placeHolders = new ArrayList<PlaceHolderBlock>();

		for(Block block : blocks) {
			addBlock(block.doCopy());
		}
	}

	@Override
	protected String[] getRequiredProperties() {
		return null;
	}

	public void addBlock(Block block) {
		blockMap.put(block.getName(), block);
		if(block instanceof PlaceHolderBlock) {
			placeHolders.add((PlaceHolderBlock)block);
		}
	}

	public Block getBlock(String blockName) {
		Block block = blockMap.get(blockName);
		if(block != null) {
			return block;
		}
		
//		for(PlaceHolderBlock placeHolder : placeHolders) {
//			block = placeHolder.getBlock(blockName);
//			if(block != null) {
//				return block;
//			}
//		}
		
		return null;
	}

	public void setBlock(Block block) {
		// TODO Auto-generated method stub
	}

	public Collection<Block> getBlocks() {
		return blockMap.values();
	}
	
	@Override
	public Block doCopy() {
		PlaceHolderBlock placeHolder = (PlaceHolderBlock) super.doCopy();
		for(Block block : blockMap.values()) {
			addBlock(block.doCopy());
		}
		return placeHolder;
	}

	public int getMinOccurs() {
		return minOccurs;
	}

	public int getMaxOccurs() {
		return maxOccurs;
	}

	public boolean containsBlock(String blockName) {

		return getBlock(blockName) != null;
	}
	
	@Override
	public String toString() {
		String toString = super.toString();
		toString += "\r\n" + blockMap;
		return toString;
	}

}
